<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/17 0017
 * Time: 15:37
 */

namespace app\index\controller;


use think\Controller;
use think\exception\ErrorException;
use think\Request;
use think\Db;
class Taoauth extends Controller
{
    /**
     * 授权获取code
     * @return mixed
     */
    public function get_code()
    {
        $request = Request::instance();
        $url = $request->domain();
        $url = 'https://oauth.taobao.com/authorize?response_type=code&client_id='.config('web.WEB_TBKEY').'&view=web&redirect_uri='.$url.'/taoauth/get_access_token';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $output = curl_exec($ch);
        curl_close($ch);
//        dump($output);
        return $output;
    }

    /**
     * 授权获取access_token用户信息
     */
    public function get_access_token()
    {
        $request = Request::instance();
        $tbkurl = $request->domain();
        $url = 'https://oauth.taobao.com/token';
        $postfields= array('grant_type'=>'authorization_code',
            'client_id'=>config('web.WEB_TBKEY'),
            'client_secret'=>config('web.WEB_TBSECREC'),
            'code'=>input('get.code'),
            'redirect_uri'=>$tbkurl,
            'view'=>'wap'
        );
        $post_data = '';

        foreach($postfields as $key=>$value){
            $post_data .="$key=".urlencode($value)."&";
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);

        //指定post数据
        curl_setopt($ch, CURLOPT_POST, true);

        //添加变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_data,0,-1));
        $output = curl_exec($ch);
        curl_close($ch);
        $resp = json_decode($output);
        $resp = object_to_array($resp);
        if($resp){
            try{
                DB::table('tbk_member')->where('userid',session('userid'))->update(['taobao_user_id'=>$resp['taobao_user_id']]);
            }catch(ErrorException $errorException){
                return json(['code'=>0,'msg'=>'授权成失败']);
            }
            $this->success('授权成功', 'Member/set');
//            echo "<script>alert('授权成功');</script>";
//            header("location:".$tbkurl."/Member/set");
//            exit;
        }else{
            return json(['code'=>0,'msg'=>'授权成失败']);
        }
    }
}